package com.ffsky.litepack;

import android.app.Application;
import android.content.Context;

import com.ffsky.litepack.app.AppConf;
import com.ffsky.litepack.app.AppInterface;
import com.ffsky.litepack.cache.KVCache;
import com.ffsky.litepack.cache.KVTableCache;
import com.ffsky.litepack.dao.DataBaseManager;
import com.ffsky.litepack.storage.StorageUtil;
import com.ffsky.litepack.task.SkyTask;
import com.ffsky.litepack.task.TaskImpl;

/**
 * 全局模块类
 * @author drl
 */
public final class Lite {


    /**
     * 全局上下文
     */
    private static  Context appConnect;
    /**
     * 持久化kv缓存
     */
    public  static  KVCache kvCache;
    /**
     * 多线程
     */
    public  static  SkyTask task;
    /**
     * 只读配置项
     */
    public  static  AppConf appConf;
    /**
     * 全局app接口
     */
    public  static  AppInterface appInterface;

    /**
     * 初始化的方法
     * @param builder
     */
    public final static void install(Builder builder) {
        appConnect = builder.appContext;
        DataBaseManager.install(appConnect, builder.dataBaseName, builder.dataBaseVersion);
        if (builder.kvCache == null) {
            kvCache = new KVTableCache();
        } else {
            kvCache = builder.kvCache;
        }
        Lite.appInterface = builder.appInterface;
        appConf = builder.conf;
        StorageUtil.init(null);
        task = new TaskImpl();
    }

    /**
     * 销毁,释放单例模式
     */
    public final static void unInstall() {
        if (task != null) {
            task.destroy();
            task = null;
        }
        DataBaseManager.unInstance();
        kvCache = null;
        appConnect = null;
    }

    /**
     *  全局上下文
     * @return
     */
    public final static Context getContext() {
        return appConnect;
    }

    public static class Builder {
        public AppConf conf;
        public KVCache kvCache;
        public Context appContext;
        public AppInterface appInterface;
        public int dataBaseVersion = 10;
        public String dataBaseName = "database.db";

        public Builder setApplication(Application application) {
            appContext = application.getApplicationContext();
            return this;
        }

        public Builder setAppInterface(AppInterface appInterface) {
            this.appInterface = appInterface;
            return this;
        }

        public Builder setAppConf(AppConf appConf){
            this.conf = appConf;
            return this;
        }

        public Builder setKVCache(KVCache kv) {
            kvCache = kv;
            return this;
        }

        public Builder setDataBaseName(String dbName) {
            dataBaseName = dbName;
            return this;
        }

        public Builder setDataBaseVersion(int dbVersion) {
            dataBaseVersion = dbVersion;
            return this;
        }
        public void apply(){
            install(this);
        }

    }

}
